import Vue from 'vue'
import VueRouter from 'vue-router'
import HomePage from '@/views/HomePage.vue'
import store from '@/store';
import { Message } from 'element-ui';
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: HomePage,
      children: [
        {
          path: '/',
          name: 'Index',
          component: () => import('@/views/Index')
        },
        {
          path: '/:type/all',
          name: 'BlogAllCategoryTag',
          component: () => import('@/views/category/BlogAllCategoryTag')
        },
        {
          path: '/:type/:id',
          name: 'BlogAllCategoryTag',
          component: () => import('@/views/blog/BlogCategoryTag')
        },
        {
          path: '/view/:id',
          name: 'BlogView',
          component: () => import('@/views/blog/BlogView')
        },
      ]
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/Register')
    },
    {
      path: '/login',
      name: 'Login',
      component: ()=>import('@/views/Login')
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (store.state.token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (store.state.account.length === 0) {
        store.dispatch('getUserInfo').then(() => {
          next();
        }).catch(() => {
          Message({
            type: 'warning',
            showClose: true,
            message: '登录已过期'
          });
          next({ path: '/login' });
        })
      } else {
        next();
      }
    }
  } else {
    if (to.matched.some(r => r.meta.requireLogin)) {
      Message({
        type: 'warning',
        showClose: true,
        message: '请先登录哦'
      })
    } else {
      next();
    }
  }
})

export default router